import React from 'react';
import { connect } from 'react-redux';
import {Checkbox, Tabs, Button, Spin, message} from 'antd';
const TabPane = Tabs.TabPane;
import 'styles/setting/sub-application/sub-application-layout-setting.scss'
import subApplicationService from 'containers/setting/sub-application/sub-application.service'
import {messages} from "share/common";
import noInfo from "images/no-info.png";
import Dragger from "components/template/dragger/dragger";
import menuRoute from "routes/menuRoute";

class SubApplicationLayoutSetting extends React.Component{
  constructor(props){
    super(props);
    const dragactInit = {
      containerWidth: 0,
      className: 'normal-layout',
      margin: [0, 0],
      col: 24,
      rowHeight: 100,
      layout: [],
      draggableHeight: 50,
    };
    this.state = {
      list: [],
      sort: [],
      dragactInit,
      containerWidth: 400,  //右侧页面宽度
      loading: false,
      dataLoading: false,
      allDataLoading: false,
      subApplicationPage: menuRoute.getRouteItem('sub-application','key'),    //子应用管理的页面项
    };
  }

  componentWillMount() {
    this.getDefaultApplication();
  }

  getDefaultApplication = () => {
    const {sort} = this.state;
    this.setState({
      dataLoading: true,
    });
    subApplicationService.getDefaultApplication().then(res => {
      res.data.length && res.data.map(item => {
        sort.push(item)
      });
      this.setState({
        dataLoading: false,
      }, () => {
        this.getEnabledSubApplicationList();
        this.getLayoutData(sort);
      });
    }).catch(err => {
      this.setState({
        dataLoading: false,
      });
    })
  };

  getEnabledSubApplicationList = () => {
    this.setState({
      allDataLoading: true,
    });
    subApplicationService.getEnabledSubApplicationList().then(res => {
      this.setState({
        list: res.data,
        allDataLoading: false,
      })
    }).catch(err => {
      this.setState({
        allDataLoading: false,
      });

    })
  };

  onCheckboxChange = (e, item) => {
    const {sort, dragactInit, list} = this.state;
    let sortCopy = [];
    let arr = [];
    dragactInit.layout.map((item, index) => {
      arr.push(dragactInit.layout.filter(layout => layout.order === index)[0].name)
    });
    arr.map(array => {
      list.length && list.map(item => {
        if (item.tenantWidgetDetail && item.tenantWidgetDetail.length) {
          item.tenantWidgetDetail.map((param) => {
            if(param.appCode === array){
              sortCopy.push(param)
            }
          })
        }
      });
    });
    if(e.target.checked){
      sortCopy.push(item)
    }else{
      sortCopy.map((param, index) => {
        if(param.appCode === item.appCode){
          sortCopy.splice(index, 1)
        }
      });
    }
    this.getLayoutData(sortCopy);
  };

  getLayoutData = (sort) => {
    const { dragactInit, containerWidth } = this.state;
    let layout = [];
    sort.length && sort.map((item, index) =>{
      layout.push({w: 6, h: 1, key: index, order: index, show: true, removable: true, firm: true, name: item.appCode})
    });
    this.setState({
      sort,
      dragactInit: Object.assign(dragactInit, {containerWidth, layout: layout,})
    });
  };

  //刷新布局
  refreshLayout = (layout) => {
    const {dragactInit} = this.state;
    this.setState({dragactInit: Object.assign(dragactInit, {layout})})
  };

  handleSave = () => {
    const {dragactInit} = this.state;
    let arr = [];
    dragactInit.layout.map(item => {
      arr.push({appCode: undefined})
    });
    dragactInit.layout.map(item => {
      arr.splice(item.order, 1, {appCode: item.name})
    });
    this.setState({
      loading: true,
    });
    subApplicationService.updateDefaultApplication(arr).then(res => {
      message.success(messages('setting.key211')/*保存成功*/);
      this.setState({
        loading: false,
      });
      this.handleBack();
    }).catch(err => {
      this.setState({
        loading: false,
      })
    })
  };

  handleBack = () => {
    const {subApplicationPage} = this.state;
    this.context.router.replace(subApplicationPage.url)
  };

  render() {
    const {list, sort, dragactInit, loading, dataLoading, allDataLoading} = this.state;
    return (
      <div className={"sub-application-layout-setting"}>
        <div className={"layout-setting-head"}>
          <span className={"font-setting"}>{messages('setting.key2015')/*常用功能设置及排序*/}&nbsp;&nbsp;</span>
          <span style={{fontSize: 12, color: "#999999"}}>{messages('setting.key2016')/*App首页的常用功能区，每位员工最多可以显示11个*/}</span>
        </div>
        <div className={"layout-setting-body"}>
          <div className={"layout-setting-body-left"}>
            <div className={"layout-setting-description"}>
              <div className="layout-setting-step-no">1</div>
              <div className={"layout-setting-step-text"}>{messages('setting.key2017')/*步骤一*/}</div>
              <div className={"layout-setting-border"}/>
            </div>
            <div className={"font-setting margin-left"}>{messages('setting.key2018')/*勾选应用添加至常用功能*/}</div>
            <div className={"body-left-content"}>
            {
              list.length ? list.map(item => {
                return(
                  item.sectionCode !== "SCAN" &&
                  <div className={"margin-left"} key={item.sectionCode}>
                    <div className="body-left-title">{item.sectionName}</div>
                    {
                      item.tenantWidgetDetail && item.tenantWidgetDetail.length && item.tenantWidgetDetail.map((param) =>{
                        return(
                          <div className="body-left-item" key={param.appCode}>
                            <Checkbox checked={sort.filter(sort => sort.appCode === param.appCode).length}
                                      onChange={(e) => this.onCheckboxChange(e, param)}>
                              {param.appName}
                            </Checkbox>
                          </div>
                        )
                      })
                    }
                  </div>
                )
              })
                : <Spin spinning={allDataLoading}/>
            }
          </div>
          </div>
          <div className={"layout-setting-body-right"}>
            <div className={"layout-setting-description"}>
              <div className="layout-setting-step-no">2</div>
              <div className={"layout-setting-step-text"}>{messages('setting.key2019')/*步骤二*/}</div>
              <div className={"layout-setting-border"}/>
            </div>
            <div className={"font-setting margin-left"}>{messages('setting.key2020')/*拖拽进行常用应用排序*/}</div>
            <div className={"body-right-container margin-left"}>
              {
                sort.length ?
                <Dragger {...dragactInit}
                       isOperating={true}
                       show={false}
                       draggingStyle={{background: "#e9e9e9",}}
                       refresh={(layout) => this.refreshLayout(layout)}>
                  {
                    sort.map(item => {
                      return (
                        <div className={"body-right-block"} key={item.appCode}>
                          <div className={"body-right-block-content"}>
                            <div className={"body-right-block-image"}>
                              <img alt=" "
                                   src={item.appIcon ? item.appIcon : noInfo}
                                   style={{height: 44, width: 44}}/>
                            </div>
                            <div className={"body-right-block-name"}>{item.appName}</div>
                          </div>
                        </div>
                      )
                    })
                  }
              </Dragger>
                  : <Spin spinning={dataLoading}/>
              }
            </div>
          </div>
          <div className={"clear"}/>
        </div>
        <div className={"footer-buttons-area"}>
            <Button type={"primary"}
                    loading={loading}
                    style={{marginRight: 15}}
                    onClick={this.handleSave}>{messages('setting.key1079')/*保存*/}</Button>
            <Button onClick={this.handleBack}>{messages('setting.key1114')/*返回*/}</Button>
        </div>
      </div>
    );
  }
}

SubApplicationLayoutSetting.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
  }
}

export default connect(mapStateToProps)(SubApplicationLayoutSetting);
